import React, { useContext, useState } from 'react';
import classes from './Cart.module.css';
import CartContext from "@/store/cartContext";
import CartDetails from './CartDetails/CartDetails'
import Checkout from './checkOut/CheckOut'

const Cart = () => {
  const ctx = useContext(CartContext);
  const iconImg = '/img/test.png'
  // 是否显示详情
  const [showDetails, setShowDetails] = useState(false)
  const showDetailFun = () => {
    if (ctx.totalAmount === 0) {
      setShowDetails(false)
      return
    }
    setShowDetails(preState => !preState)
  }
  // 结账页显示隐藏
  const [showCheckOut, setShowCheckOut] = useState(false)
  const showCheckOutFun = () => {
    if (ctx.totalAmount === 0) return
    setShowCheckOut(true)
  }
  const hideCheckOutFun = () => {
    setShowCheckOut(false)
  }

  return (
    <div className={classes.Cart} onClick={showDetailFun}>
      {showCheckOut && <Checkout onHide={hideCheckOutFun}></Checkout>}
      {/* 购物车详情 */}
      {(showDetails && ctx.totalAmount != 0) ? <CartDetails></CartDetails> : null}

      <div className={classes.Icon}>
        <img src={iconImg} />
        {ctx.totalAmount === 0 ? null : <span className={classes.TotalAmount}>{ctx.totalAmount}</span>}
      </div>
      {ctx.totalAmount === 0 ? <p className={classes.noMeal}>未选购商品</p> : <p className={classes.Price}>{ctx.totalPrice}</p>}
      <button
        onClick={showCheckOutFun}
        className={`${classes.Button} ${ctx.totalAmount === 0 ? classes.disabled : ''}`}>去结算</button>
    </div>
  );
};

export default Cart;
